package ch.il07.converter.persistance.tests;

import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.util.List;

import org.junit.Before;
import org.junit.Test;

import ch.il07.converter.persistence.Persistence;
import ch.il07.converter.persistence.PersistenceHelper;
import ch.il07.converter.persistence.entities.AccessLevel;
import ch.il07.converter.persistence.entities.Measurand;
import ch.il07.converter.persistence.entities.Unit;
import ch.il07.converter.persistence.exceptions.AlreadyDefinedException;
import ch.il07.converter.persistence.exceptions.NoSuchMeasurandException;
import ch.il07.converter.persistence.exceptions.PersistenceException;
import ch.il07.utils.RandomHelper;

public class GetMeasurand {

	private Persistence persistence;

	@Before
	public void setUp() {
		try {
			persistence = PersistenceHelper.getPersistence();
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void getMeasurandNormal() {

		String username = RandomHelper.randString();
		String measurandName = RandomHelper.randString();

		{ // insert measurand
			try {
				persistence.addUser(username, RandomHelper.getEmail(username), username, AccessLevel.USER);
				assertNotNull("user '"+username+"' should exist in db", persistence.getUser(username, username));
				
				Measurand m = new Measurand(measurandName, new Unit(RandomHelper.randString(), 1D));
				persistence.addMeasurand(m, username);
				
				// check their existence
				List<Measurand> measurands = persistence.getMeasurands(username);

				boolean measurandIsAvailable = false;
				for (Measurand measurand : measurands) {
					if (measurand.getName().equals(measurandName)) {
						measurandIsAvailable = true;
						break;
					}
				}
				assertTrue("measurand '" + measurandName + "' should exist in db",
						measurandIsAvailable);
			} catch (AlreadyDefinedException e) {
				fail(e.getMessage());
			} catch (PersistenceException e) {
				fail(e.getMessage());
			}
		}

		try {
			Measurand m = persistence.getMeasurand(measurandName, username);
			assertNotNull(
					"measurand '"+measurandName+"' for user '"+username+"' must exist in db", m);
			assertNotNull("default Unit must be set!", m.getDefaultUnit());
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}

	@Test
	public void getMeasurandNotExistMeasurandString() {
		String username = RandomHelper.randString();

		try {
			persistence.addUser(username, RandomHelper.getEmail(username), username, AccessLevel.USER);
			persistence.getMeasurand("FalscheEingabe", username);
		} catch (NoSuchMeasurandException e) {
			// expected
		} catch (PersistenceException e) {
			fail(e.getMessage());
		}
	}
}